package com.gmail.yesguxun.util;

import java.util.LinkedList;
import java.util.Vector;

import com.gmail.yesguxun.util.EventBus.EventHandlers;

public class EventBusAsync extends EventBus {
       
    
    private boolean mRunning = false;    
    private LinkedList<EventBusEventObj> mEventList;
    
    private LogX mLog = LogFactory.getLogObject();
    
    protected EventBusAsync()
    {
        super();
        mEventList = new LinkedList<EventBusEventObj>();
    }
    
    public synchronized void start()
    {
        if(this.mRunning != true){
            Thread thread;
            thread = new Thread(new InternalRunnable());
            thread.setDaemon(true);
            this.mRunning = true;
            thread.start();
        }            
    }
    
    public synchronized void stop()
    {
        this.mRunning = false;
    }
    
    public static synchronized EventBusAsync getInstance()
    {
        if(EventBus.m_eventBusInstance == null)
        {
            EventBus.m_eventBusInstance = new EventBusAsync();
            ((EventBusAsync)EventBus.m_eventBusInstance).start();
        }
      
        return (EventBusAsync)EventBus.m_eventBusInstance;
    }
    
    private class InternalRunnable implements Runnable {
        public void run() {
            internalRun();
        }
    }
           
    private void internalRun() {
        while(mRunning) {
            if(mEventList.isEmpty())
            {
                try
                {
                    this.mLog.debug("tumblr", "EventBus Thread waiting for new event");
                    synchronized(this.mEventList){
                        mEventList.wait();
                    }
                } catch (InterruptedException e)
                {
                    stop();
                }
              
            }
            
            EventBusEventObj eventObj = null;
            synchronized(this.mEventList)
            {
                eventObj = this.mEventList.removeLast();
            }
            
            //the super file event to call onEvent methods of handler objects
            this.mLog.debug("tumblr", "Call Sync firEvent: " + eventObj.getEventType());
            super.fireEvent(eventObj);          
        }
    }
    
    public void fireEvent(EventBusEventObj eventObj)
    {
        synchronized(this.mEventList)
        {
            this.mEventList.addFirst(eventObj);
            this.mEventList.notify();
        }
    }
}
